package org.asiainfo.file.service.impl;

import com.alibaba.nacos.common.utils.IoUtils;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.asiainfo.common.core.enums.UploadType;
import org.asiainfo.common.core.utils.MapstructUtils;
import org.asiainfo.common.core.utils.SpringUtils;
import org.asiainfo.file.config.properties.FastDfsProperties;
import org.asiainfo.file.domain.AttactmentInfo;
import org.asiainfo.file.domain.bo.AttactmentInfoBo;
import org.asiainfo.file.domain.vo.AttactmentInfoVo;
import org.asiainfo.file.mapper.AttactmentInfoMapper;
import org.asiainfo.file.service.AttactmentInfoService;
import org.asiainfo.file.service.FileStrategy;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * FastDFS 文件策略
 *
 * @author dotor-ww
 */
@Service("fastDfs" + FileStrategy.BASE_NAME)
@RequiredArgsConstructor
@Slf4j
public class FastDfsFileStrategy implements FileStrategy {

    private final FastDfsProperties fastDfsProperties;

    private final FastFileStorageClient storageClient;

    private final AttactmentInfoMapper attactmentInfoMapper;

    /**
     * 上传附件
     *
     * @param attactmentInfoBo 附件信息
     * @param file             文件
     * @return 上传结果
     */
    @Override
    public AttactmentInfoVo uploadFile(AttactmentInfoBo attactmentInfoBo, MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        StorePath storePath = storageClient.uploadFile(inputStream, file.getSize(), file.getOriginalFilename(), null);
        IoUtils.closeQuietly(inputStream);
        String fileUrl = String.join("/", fastDfsProperties.getTenantDomain(), storePath.getFullPath());
        AttactmentInfo attactmentInfo = SpringUtils.getBean(AttactmentInfoService.class)
            .buildAttactmentInfo(attactmentInfoBo.getAttactId(), fileUrl, file);
        attactmentInfo.setUploadType(UploadType.FAST_DFS.getCode());
        attactmentInfo.setFileName(file.getOriginalFilename());
        attactmentInfoMapper.insertSelective(attactmentInfo);
        return MapstructUtils.convert(attactmentInfo, AttactmentInfoVo.class);
    }
}
